<?php

class Silk_Mapi_Model_Api2_Shipping_Rest_Admin_V1 extends Silk_Mapi_Model_Api2_Shipping_Rest
{
    /**
     * @var Silk_Tms_Model_Shipping_Order
     */
    protected $tmsOrder;

    public $_incrementId = 0;

    /**
     * @var array
     */
    protected $qtys;

    public function _create($data)
    {
        $shipOrder = $this->getTmsOrder();
        $incrementId = $shipOrder->getIncrementId();
        $shippingId = $this->getRequest()->getParam('id');
        Mage::register('shipping_id',$shippingId);
        /** @var Silk_Tms_Helper_Pickup $helper */
        $helper = Mage::helper('tms/pickup');

        try {
            $helper->pickup($incrementId);
        } catch (Exception $e) {
            $this->_critical($e->getMessage(), $e->getCode());
        }

        return $this->getShippingOrdersByOrder();
    }

    /**
     * @return Silk_Tms_Model_Shipping_Order
     * @throws Exception
     * @throws Mage_Api2_Exception
     */
    protected function getTmsOrder()
    {
        if (!$this->tmsOrder) {
            if ($this->_incrementId) {
                $incrementId = $this->_incrementId;
            } else {
                $incrementId = $this->getParam('increment_id');
            }

            if (!$incrementId) {
                $this->_critical('缺少参数2！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
            }

            /** @var Silk_Tms_Model_Shipping_Order $order */
            $order = Mage::getModel('tms/shipping_order')->load($incrementId, 'increment_id');
            if ($order && $order->getId()) {
                $this->tmsOrder = $order;
            } else {
                $this->_critical('当前订单不存在！', Mage_Api2_Model_Resource::ERROR_CHECKOUT_ORDER_NOT_FOUND);
            }
        }

        return $this->tmsOrder;
    }

    protected function getShippingOrdersByOrder()
    {
        $shippingId = $this->getShippingId();
        /** @var Silk_Tms_Model_Mysql4_Shipping_Order_Collection $collection */
        $collection = Mage::getModel('tms/shipping_order')->getCollection()
            ->addFieldToFilter('shipping_id', array('eq' => $shippingId));

        return $this->formatOrderCollection($collection);
    }
}
